const router = require('koa-router')()
const util = require('../utils/util')
const Role = require('../models/roleSchema')

router.prefix('/roles')

// 菜单列表查询
router.get('/allList', async (ctx) => {
    try {
        const list = await Role.find({}, "_id roleName")
        ctx.body = util.success(list)
    } catch (error) {
        ctx.body = util.fail(`查询异常:${error.stack}`)
    }
})

// 菜单列表查询
router.get('/list', async (ctx) => {
    try {
        const {
            roleName
        } = ctx.request.query;
        const {
            page,
            skipIndex
        } = util.pager(ctx.request.query)
        const params = {}
        if (roleName) params.roleName = roleName;
        // 根据条件查询所有用户列表
        const query = Role.find(params)
        const list = await query.skip(skipIndex).limit(page.pageSize)
        const total = await Role.countDocuments(params);
        ctx.body = util.success({
            page: {
                ...page,
                total
            },
            list
        })
    } catch (error) {
        ctx.body = util.fail(`查询异常:${error.stack}`)
    }
})


// 菜单编辑、删除、新增功能
router.post('/operate', async (ctx) => {
    const {
        _id,
        action,
        ...params
    } = ctx.request.body;
    let res, info;
    try {
        if (action == 'add') {
            res = await Role.create(params)
            info = '创建成功'
        } else if (action == 'edit') {
            params.updateTime = new Date();
            res = await Role.findByIdAndUpdate(_id, params);
            info = '编辑成功'
        } else {
            res = await Role.findByIdAndRemove(_id)
            await Role.deleteMany({
                parentId: {
                    $all: [_id]
                }
            })
            info = '删除成功'
        }
        ctx.body = util.success('', info);
    } catch (error) {
        ctx.body = util.fail(error.stack);
    }

})

// 设置权限
router.post('/permission', async (ctx) => {
    const {
        _id,
        ...params
    } = ctx.request.body;
    let res, info;
    try {
        params.updateTime = new Date();
        res = await Role.findByIdAndUpdate(_id, params);
        info = '权限设置成功'
        ctx.body = util.success('', info);
    } catch (error) {
        ctx.body = util.fail(error.stack);
    }

})

module.exports = router;